<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增设备信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :validate-on-rule-change="false">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备编码" prop="equipmentCode">
              <div v-if="autoGenerateCodes">
                <el-input 
                  :value="form.equipmentCode || '等待选择设备类型后自动生成...'" 
                  placeholder="请选择设备类型后自动生成"
                  disabled
                  style="width: calc(100% - 110px)"
                ></el-input>
                <el-checkbox v-model="autoGenerateCodes" style="margin-left: 10px;" @change="handleAutoGenerateCodesChange">
                  自动生成
                </el-checkbox>
                <el-button v-if="form.equipmentTypeId" type="text" @click="forceGenerateCode" style="margin-left: 10px;">
                  重新生成
                </el-button>
              </div>
              <div v-else>
                <el-input 
                  ref="equipmentCodeInput"
                  v-model="form.equipmentCode" 
                  placeholder="请输入设备编码"
                  @blur="checkEquipmentCodeExist"
                  style="width: calc(100% - 110px)"
                ></el-input>
                <el-checkbox v-model="autoGenerateCodes" style="margin-left: 10px;" @change="handleAutoGenerateCodesChange">
                    自动生成
                  </el-checkbox>
              </div>
              <div v-if="equipmentCodeExists" class="el-form-item__error">
                该设备编码已存在，请更换
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeId">
              <el-cascader
                ref="typeSelector"
                v-model="form.equipmentTypeId"
                :options="typeTreeOptions"
                :props="{ 
                  checkStrictly: true,
                  value: 'id',
                  label: 'label',
                  children: 'children',
                  emitPath: false
                }"
                clearable
                placeholder="请选择设备类型"
                style="width: 100%"
                @change="handleTypeChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select 
                v-model="form.workshopId" 
                placeholder="请选择车间" 
                @change="handleWorkshopChange"
                @click.native="loadWorkshopOptions" 
                style="width: 100%"
              >
                <el-option
                  v-for="item in workshopOptions"
                  :key="item.workshop_id"
                  :label="item.workshop_name"
                  :value="item.workshop_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属生产线" prop="productionLineId">
              <el-select 
                v-model="form.productionLineId" 
                placeholder="请选择生产线" 
                @change="handleProductionLineChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in productionLineOptions"
                  :key="item.production_line_id"
                  :label="item.production_line_name"
                  :value="item.production_line_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备状态" prop="equipmentStatus">
              <el-select v-model="form.equipmentStatus" placeholder="请选择设备状态" style="width: 100%">
                <el-option label="空闲" value="0" />
                <el-option label="在用" value="1" />
                <el-option label="维修中" value="2" />
                <el-option label="报废" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">规格信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="specifications">
              <el-input v-model="form.specifications" placeholder="请输入设备规格" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                placeholder="请选择采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="采购价格" prop="purchasePrice">
              <el-input-number v-model="form.purchasePrice" :precision="2" :step="1000" :min="0" controls-position="right" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备照片" prop="imageUrl">
              <el-upload
                class="avatar-uploader"
                action="#"
                name="avatarfile"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :http-request="uploadFile">
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">管理与维护</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="管理人" prop="responsiblePerson">
              <el-input 
                v-model="form.responsiblePerson" 
                placeholder="请选择管理人员" 
                readonly
                @click.native="openUserSelectDialog"
              >
                <el-button slot="append" icon="el-icon-user" @click.stop="openUserSelectDialog">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="departmentName">
              <el-input 
                v-model="form.departmentName" 
                placeholder="选择管理人后自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="resetForm">重 置</el-button>
          <el-button @click="goBack">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择管理人员" :visible.sync="userSelectVisible" width="800px" append-to-body>
      <!-- 搜索区域 -->
      <el-form :model="userQueryParams" ref="userQueryForm" :inline="true">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="userQueryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="handleUserReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table
        v-loading="userLoading"
        :data="userList"
        @row-click="selectUser"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="userName" label="用户名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="nickName" label="用户昵称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="phonenumber" label="手机号码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="dept.deptName" label="部门" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.dept ? scope.row.dept.deptName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click.stop="selectUser(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="loadUserList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { addEquipment, generateEquipmentCode, checkEquipmentCode, checkEquipmentCodeExists } from "@/api/sb/equipmentLedger";
import { listEquipmentType, getEquipmentTypeTree } from "@/api/sb/equipmentType";
import { uploadEquipmentImage } from "@/api/common/upload";
import { listUser } from "@/api/system/user";
import { listWorkshop } from "@/api/basic/factory";
import { getProductionLinesByWorkshop } from "@/api/basic/line";
import axios from "axios";

export default {
  name: "EquipmentLedgerAdd",
  data() {
    return {
      // 是否自动生成编码
      autoGenerateCodes: true,
      // 设备编码是否已存在
      equipmentCodeExists: false,
      // 设备类型选项
      typeOptions: [],
      // 设备类型树形选项
      typeTreeOptions: [],
      // 车间选项
      workshopOptions: [],
      // 生产线选项
      productionLineOptions: [],
      // 表单参数
      form: {
        equipmentCode: '',
        equipmentName: '',
        equipmentTypeId: null,
        equipmentStatus: '0', // 默认设置为"空闲"
        location: '',
        departmentName: '',
        departmentId: null,
        model: '',
        specifications: '',
        manufacturer: '',
        purchaseDate: '',
        purchasePrice: 0,
        imageUrl: '',
        responsiblePerson: '',
        userId: null, // 管理人ID
        userNickName: '', // 用户昵称
        remark: '',
        workshopId: null, // 车间ID
        productionLineId: null // 生产线ID
      },
      // 表单校验
      rules: {
        equipmentCode: [
          { required: true, message: "设备编码不能为空", trigger: "change" }
        ],
        equipmentName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        equipmentTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        equipmentStatus: [
          { required: true, message: "设备状态不能为空", trigger: "change" }
        ],
        workshopId: [
          { required: true, message: "所属车间不能为空", trigger: "change" }
        ],
        productionLineId: [
          { required: true, message: "所属生产线不能为空", trigger: "change" }
        ],
        responsiblePerson: [
          { required: true, message: "管理人不能为空", trigger: "blur" }
        ]
      },
      // 用户选择相关
      userSelectVisible: false,
      userLoading: false,
      userList: [],
      userTotal: 0,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 生产线加载状态
      loadingProductionLines: false,
      // 车间加载状态
      loadingWorkshops: false
    };
  },
  created() {
    this.getTypeOptions();
    // 初始化车间选项，确保仅在首次加载时执行一次
    this.$nextTick(() => {
      this.loadWorkshopOptions();
    });
    // 初始化时不自动生成编码，等待选择设备类型后再生成
  },
  
  mounted() {
    // 组件挂载完成后不再重复加载车间数据
  },
  
  watch: {
    // 监听设备类型变化，自动生成编码
    'form.equipmentTypeId': function(val) {
      if (val && this.autoGenerateCodes) {
        this.generateLocalCode();
    }
    }
    // 移除车间ID的监听，避免重复调用
  },
  
  methods: {
    // 获取设备类型选项
    getTypeOptions() {
      getEquipmentTypeTree().then(response => {
        console.log('设备类型树形数据:', response);
        if (response.code === 200 && response.data) {
          this.typeTreeOptions = this.formatTreeData(response.data);
        } else {
          this.typeTreeOptions = [];
          console.error("获取设备类型树形列表失败:", response);
        }
      }).catch(error => {
        console.error("获取设备类型树形列表错误:", error);
      });
    },
    
    // 格式化树形数据
    formatTreeData(data) {
      return data.map(item => {
        const node = {
          id: item.id || item.typeId,
          label: item.label || item.typeName,
          typeId: item.id || item.typeId,
          typeCode: item.typeCode,
          children: item.children && item.children.length > 0 ? this.formatTreeData(item.children) : []
        };
        return node;
      });
    },
    
    // 自动生成编码开关变更
    handleAutoGenerateCodesChange(val) {
      console.log("自动生成编码开关变更:", val);
      
      if (val) {
        // 开启自动生成编码
        if (this.form.equipmentTypeId) {
          // 已选择设备类型，立即生成编码
          this.generateLocalCode();
        } else {
          this.$message.warning("请选择设备类型后，系统将自动生成编码");
        }
      } else {
        // 关闭自动生成编码，清空编码
        this.form.equipmentCode = '';
        this.equipmentCodeExists = false;
      }
    },
    
    // 本地生成编码，避免依赖后端接口
    generateLocalCode() {
      // 直接使用硬编码值简化处理
      const now = new Date();
      const dateStr = now.getFullYear().toString().substring(2) + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0');
      const randomCode = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      
      // 使用EQ前缀
      const generatedCode = `EQ-${dateStr}-${randomCode}`;
      
      // 更新表单
      this.form.equipmentCode = generatedCode;
      console.log("自动生成的编码:", generatedCode);
      
      // 强制更新视图
      this.$forceUpdate();
    },
    
    // 设备类型变更
    handleTypeChange(value) {
      console.log("设备类型变更:", value);
      
      // 更新表单中的设备类型ID
      this.form.equipmentTypeId = value;
      
      // 如果启用了自动生成编码且选择了类型，生成编码
      if (this.autoGenerateCodes && value) {
        // 先显示正在生成的提示
        this.form.equipmentCode = "正在生成编码...";
        
        // 直接使用硬编码值简化处理
        const now = new Date();
        const dateStr = now.getFullYear().toString().substring(2) + 
              String(now.getMonth() + 1).padStart(2, '0') + 
              String(now.getDate()).padStart(2, '0');
        const randomCode = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        
        // 使用EQ前缀
        const generatedCode = `EQ-${dateStr}-${randomCode}`;
        
        // 稍微延迟更新以显示加载效果
        setTimeout(() => {
          this.form.equipmentCode = generatedCode;
          console.log("自动生成的编码:", generatedCode);
        }, 500);
      }
    },
    
    // 生成设备编码
    generateEquipmentCode() {
      const typeId = this.form.equipmentTypeId;
      if (!typeId) {
        this.$message.warning("请先选择设备类型");
        return;
      }
      
      // 查找选中的设备类型节点
      const findNode = (nodes, id) => {
        for (let node of nodes) {
          if (node.id === id) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const foundInChild = findNode(node.children, id);
            if (foundInChild) return foundInChild;
          }
        }
        return null;
      };
      
      // 获取类型编码
      let typeCode = "EQ";
      const selectedType = findNode(this.typeTreeOptions, typeId);
      console.log("找到的设备类型节点:", selectedType);
      if (selectedType && selectedType.typeCode) {
        typeCode = selectedType.typeCode;
      } else {
        console.log("未找到类型编码，使用默认编码EQ");
      }
      
      console.log("使用设备类型编码生成:", typeCode);
      
      // 设置加载状态
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在生成设备编码...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 使用标准API调用
      generateEquipmentCode(typeCode).then(response => {
        loadingInstance.close();
        if (response.code === 200) {
          const code = response.data || '';
          console.log("生成的设备编码:", code);
          
          // 使用多种方法确保表单更新
          this.form.equipmentCode = code;
          this.$set(this.form, 'equipmentCode', code);
          
          // 强制更新视图和验证
          this.$nextTick(() => {
            // 手动更新DOM
            if (this.$refs.equipmentCodeInput && this.$refs.equipmentCodeInput.$el) {
              const inputEl = this.$refs.equipmentCodeInput.$el.querySelector('input');
              if (inputEl) {
                inputEl.value = code;
                // 触发输入事件
                const event = new Event('input', { bubbles: true });
                inputEl.dispatchEvent(event);
              }
            }
            
            // 触发表单验证
            this.$refs.form.validateField('equipmentCode');
            
            console.log("更新后的表单数据:", this.form);
            this.$forceUpdate(); // 强制视图刷新
          });
          
          // 显示成功消息
          this.$message.success("设备编码生成成功");
        } else {
          this.$message.error("生成编码失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        loadingInstance.close();
        console.error("生成编码错误:", error);
        this.$message.error("生成编码失败");
      });
    },
    
    // 使用标准API调用作为备用方法
    fallbackGenerateCode(typeCode) {
      generateEquipmentCode(typeCode).then(response => {
        if (response.code === 200) {
          const code = response.data || '';
          console.log("备用方法生成的设备编码:", code);
          // 使用Vue的响应式方法直接更新，确保视图更新
          this.$set(this.form, 'equipmentCode', code);
        } else {
          this.$message.error("备用方法生成编码失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        console.error("备用方法生成编码错误:", error);
        this.$message.error("备用方法生成编码失败");
      });
    },
    
    // 检查设备编码是否已存在
    checkEquipmentCodeExist() {
      if (!this.form.equipmentCode) {
        return;
      }
      
      checkEquipmentCodeExists(this.form.equipmentCode).then(response => {
        if (response.code === 200) {
          this.equipmentCodeExists = response.data === true;
          if (this.equipmentCodeExists) {
            this.$message.warning("设备编码已存在，请更换");
          } else {
            this.$message.success("设备编码可用");
          }
        }
      }).catch(error => {
        console.error("检查设备编码错误:", error);
        this.$message.error("检查设备编码失败");
      });
    },

    // 设备编码输入时触发
    onEquipmentCodeInput() {
      this.checkEquipmentCodeExist();
    },
    
    // 表单提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 如果启用了自动生成编码但还没有编码（可能是还没选择设备类型）
          if (this.autoGenerateCodes && !this.form.equipmentCode) {
            if (!this.form.equipmentTypeId) {
              this.$message.error("请先选择设备类型，以便系统生成设备编码");
              return;
            } else {
              // 有设备类型但没编码，尝试生成
              this.generateEquipmentCode();
              this.$message.warning("正在生成设备编码，请稍后再提交");
              return;
            }
          }
          
          // 先检查编码是否存在
          checkEquipmentCodeExists(this.form.equipmentCode).then(response => {
            if (response.code === 200 && response.data === true) {
              this.equipmentCodeExists = true;
            this.$message.error("设备编码已存在，请更换");
            return;
          }
          
            // 编码不存在，可以提交表单
            this.doSubmit();
          }).catch(error => {
            console.error("检查设备编码错误:", error);
            this.$message.error("检查设备编码失败，请稍后再试");
            // 出错时不提交表单，防止重复编码
          });
        }
      });
    },

    // 执行提交操作
    doSubmit() {
          // 如果选择了设备类型，获取类型名称
          if (this.form.equipmentTypeId) {
            // 查找选中的设备类型节点
            const findNode = (nodes, id) => {
              for (let node of nodes) {
                if (node.id === id) {
                  return node;
                }
                if (node.children && node.children.length > 0) {
                  const foundInChild = findNode(node.children, id);
                  if (foundInChild) return foundInChild;
                }
              }
              return null;
            };
            
            const selectedType = findNode(this.typeTreeOptions, this.form.equipmentTypeId);
            if (selectedType && selectedType.label) {
              this.form.equipmentTypeName = selectedType.label;
              console.log("设置设备类型名称:", this.form.equipmentTypeName);
            }
          }
          
          addEquipment(this.form).then(response => {
            if (response.code === 200) {
              this.$message.success("添加成功");
              this.goBack();
            } else {
              this.$message.error(response.msg || "添加失败");
            }
          }).catch(error => {
            console.error("添加设备错误:", error);
        let errorMsg = error.response && error.response.data ? error.response.data.message : "添加失败";
        this.$message.error(errorMsg);
      });
    },
    
    // 表单重置
    resetForm() {
      this.$refs["form"].resetFields();
      this.form = {
        equipmentCode: '',
        equipmentName: '',
        equipmentTypeId: null,
        equipmentStatus: '0', // 默认设置为"空闲"
        location: '',
        departmentName: '',
        departmentId: null,
        model: '',
        specifications: '',
        manufacturer: '',
        purchaseDate: '',
        purchasePrice: 0,
        imageUrl: '',
        responsiblePerson: '',
        userId: null, // 管理人ID
        userNickName: '', // 用户昵称
        remark: '',
        workshopId: null, // 车间ID
        productionLineId: null // 生产线ID
      };
      this.equipmentCodeExists = false;
    },
    // 返回列表
    goBack() {
      this.$router.push({ path: "/sb/equipment-ledger" });
    },
    // 取消按钮
    cancel() {
      this.goBack();
    },
    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      console.log("上传成功响应:", res);
      if (res && res.code === 200) {
        // 尝试从多种可能的响应格式中提取URL
        let imageUrl = '';
        
        if (res.data && res.data.url) {
          imageUrl = res.data.url;
        } else if (res.url) {
          imageUrl = res.url;
        } else if (res.imgUrl) {
          imageUrl = res.imgUrl;
        } else if (typeof res.data === 'string') {
          imageUrl = res.data;
        }
        
        if (imageUrl) {
          // 确保图片URL是完整的URL路径
          if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
            imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
          }
          
          this.form.imageUrl = imageUrl;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error('无法获取上传的图片URL');
          console.error('无法从响应中获取图片URL:', res);
        }
      } else {
        this.$message.error(res.msg || "上传失败");
      }
    },
    // 自定义上传
    uploadFile(options) {
      const { file, onSuccess, onError } = options;
      
      // 显示上传中提示
      this.$message.info('图片上传中...');
      
      console.log('准备上传图片，参数名:', 'avatarfile');
      console.log('文件类型:', file.type);
      console.log('文件大小:', file.size);
      
      // 使用原生XHR上传文件，避开axios的默认处理
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append('avatarfile', file);
      
      // 获取token
      const token = this.$store.getters.token;
      
      xhr.open('POST', process.env.VUE_APP_BASE_API + '/ldzl-sb/sb/upload/image', true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          try {
            const res = JSON.parse(xhr.responseText);
            console.log('图片上传响应:', res);
            
        if (res.code === 200) {
              // 尝试从多种可能的响应格式中提取URL
              let imageUrl = '';
              
              if (res.data && res.data.url) {
                imageUrl = res.data.url;
              } else if (res.url) {
                imageUrl = res.url;
              } else if (res.imgUrl) {
                imageUrl = res.imgUrl;
              } else if (res.data && typeof res.data === 'string') {
                imageUrl = res.data;
              } else if (res.data) {
                // 尝试从data对象中找到可能的URL字段
                const possibleFields = ['url', 'imgUrl', 'imageUrl', 'path', 'filePath', 'fileName'];
                for (const field of possibleFields) {
                  if (res.data[field]) {
                    imageUrl = res.data[field];
                    break;
                  }
                }
              }
              
              if (imageUrl) {
                // 确保图片URL是完整的URL路径
                if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                  imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
                }
                
                onSuccess(res);
              } else {
                console.error('无法从响应中获取图片URL:', res);
                onError(new Error('无法获取图片URL'));
              }
            } else {
              console.error('图片上传失败:', res);
              onError(new Error(res.msg || '图片上传失败'));
            }
          } catch (e) {
            console.error('解析响应失败:', e);
            onError(e);
          }
        } else {
          console.error('图片上传请求失败:', xhr.status);
          onError(new Error('图片上传请求失败: ' + xhr.status));
        }
      };
      
      xhr.onerror = function() {
        console.error('上传文件请求错误');
        onError(new Error('上传文件请求错误'));
      };
      
      xhr.send(formData);
    },
    // 强制生成编码
    forceGenerateCode() {
      this.generateLocalCode();
      this.$message.success("编码已重新生成");
    },
    // 加载车间选项
    loadWorkshopOptions() {
      // 避免重复加载
      if (this.loadingWorkshops) {
        console.log("车间数据正在加载中，跳过重复请求");
        return;
      }
      
      console.log("加载车间选项");
      this.loadingWorkshops = true;
      
      // 静默加载，不显示加载动画
      listWorkshop({pageSize: 100, is_delete: 0}).then(response => {
        console.log("车间查询结果:", response);
        
        if (response.code === 200) {
          if (response.rows && Array.isArray(response.rows) && response.rows.length > 0) {
            this.workshopOptions = response.rows;
            console.log("获取到车间数据:", this.workshopOptions.length, "条");
          } else if (response.data && Array.isArray(response.data) && response.data.length > 0) {
            this.workshopOptions = response.data;
            console.log("获取到车间数据:", this.workshopOptions.length, "条");
          } else {
            console.warn("未找到车间数据");
            this.workshopOptions = [];
          }
        } else {
          console.error("获取车间列表失败:", response.msg);
          // 静默处理错误，不显示提示
          this.workshopOptions = [];
        }
        
        this.loadingWorkshops = false;
      }).catch(error => {
        console.error("获取车间列表错误:", error);
        // 静默处理错误，不显示提示
        this.workshopOptions = [];
        this.loadingWorkshops = false;
      });
    },
    // 车间选择变更
    handleWorkshopChange(value) {
      console.log("选择车间:", value);
      
      // 清空生产线相关数据
      this.form.productionLineId = null; 
      this.form.productionLineName = '';
      this.productionLineOptions = []; // 先清空选项
      
      if (!value) {
        this.form.workshopName = '';
        return;
      }
      
      // 获取车间名称
      const workshop = this.workshopOptions.find(item => item.workshop_id == value);
      if (workshop) {
        this.form.workshopName = workshop.workshop_name;
        console.log("选择的车间名称:", this.form.workshopName);
      }
      
      // 加载对应的生产线选项
      this.loadProductionLineOptions(value);
    },
    // 加载生产线选项
    loadProductionLineOptions(workshopId) {
      console.log("加载生产线，车间ID:", workshopId);
      
      if (!workshopId) {
        return;
      }
      
      // 添加防抖，避免频繁调用
      if (this.loadingProductionLines) {
        console.log("已有生产线加载请求正在进行，跳过");
        return;
      }
      
      this.loadingProductionLines = true;
      
      // 仅当第一次加载或生产线选项为空时显示loading
      let loading = null;
      if (this.productionLineOptions.length === 0) {
        loading = this.$loading({
          lock: true,
          text: '加载生产线数据...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      
      getProductionLinesByWorkshop(workshopId).then(response => {
        console.log("生产线查询结果:", response);
        
        if (response.code === 200) {
          if (response.data && Array.isArray(response.data) && response.data.length > 0) {
            this.productionLineOptions = response.data;
            console.log("获取到生产线数据:", this.productionLineOptions.length, "条");
          } else if (response.rows && Array.isArray(response.rows) && response.rows.length > 0) {
            this.productionLineOptions = response.rows;
            console.log("获取到生产线数据:", this.productionLineOptions.length, "条");
          } else {
            console.warn("未找到生产线数据");
            this.productionLineOptions = [];
          }
        } else {
          console.error("获取生产线列表失败:", response.msg);
          this.productionLineOptions = [];
        }
        
        this.loadingProductionLines = false;
        if (loading) loading.close();
      }).catch(error => {
        console.error("获取生产线列表错误:", error);
        
        // 静默处理操作频繁的错误
        if (error.message && error.message.includes("操作过于频繁")) {
          console.log("忽略频繁操作错误");
        } else {
          // 其他错误可以考虑显示
          // this.$message.error("获取生产线失败，请重试");
        }
        
        this.productionLineOptions = [];
        this.loadingProductionLines = false;
        if (loading) loading.close();
      });
    },
    // 生产线选择变更
    handleProductionLineChange(value) {
      // 获取生产线名称
      const productionLine = this.productionLineOptions.find(item => item.production_line_id === value);
      if (productionLine) {
        this.form.productionLineName = productionLine.production_line_name;
        // 更新设备位置为"车间名-生产线名"
        this.form.location = `${this.form.workshopName || ''}-${productionLine.production_line_name}`;
      }
    },
    // 打开用户选择对话框
    openUserSelectDialog() {
      this.userSelectVisible = true;
      this.loadUserList();
    },

    // 加载用户列表
    loadUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userLoading = false;
        if (response.code === 200) {
          this.userList = response.rows;
          this.userTotal = response.total;
        } else {
          this.userList = [];
          this.userTotal = 0;
          this.$message.error("获取用户列表失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.userLoading = false;
        console.error("获取用户列表错误:", error);
        this.$message.error("获取用户列表失败");
      });
    },

    // 用户搜索
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.loadUserList();
    },

    // 用户重置查询
    handleUserReset() {
      this.$refs["userQueryForm"].resetFields();
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      };
      this.loadUserList();
    },

    // 选择用户
    selectUser(row) {
      this.form.userNickName = row.nickName; // 保存用户昵称
      this.form.responsiblePerson = row.nickName; // 展示用户昵称而不是用户名
      this.form.userId = row.userId; // 保存用户ID
      this.form.departmentName = row.dept ? row.dept.deptName : '';
      this.userSelectVisible = false;
      this.$message.success("已选择管理人员：" + row.nickName);
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
.el-form-item__error {
  color: #F56C6C;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}
</style> 